import edu.udo.cs.wvtool.config.WVTConfiguration;
import edu.udo.cs.wvtool.main.WVTWordVector;
import edu.udo.cs.wvtool.main.WVTool;
import edu.udo.cs.wvtool.wordlist.WVTWordList;
import net.sf.javaml.core.Dataset;
import net.sf.javaml.core.Instance;
import net.sf.javaml.core.SparseInstance;
import net.sf.javaml.tools.data.FileHandler;

import java.io.File;
import java.io.FileReader;
import java.util.SortedSet;



public class Bayes {

	private WVTool wvt = new WVTool(false);	
	private WVTConfiguration config = new WVTConfiguration();

	public String classify(String inputText) throws Exception{
		
		Dataset data =  FileHandler.loadSparseDataset(new File("output2.txt"), 0, "\t",":");
		WVTWordList wordList = new WVTWordList(new FileReader("wordlist.txt"));	
		WVTWordVector newVector = wvt.createVector(inputText, wordList);
		double[] values = newVector.getValues();
//		Integer label = newVector.getDocumentInfo().getClassValue();
		Instance instance = new SparseInstance(values.length);
//		instance.setClassValue(label);		
		for(int i = 0; i < values.length; i++) {
			if(values[i] > 0.0) {
				instance.put(i, values[i]);
			}
		}
		//P(C) = frekvensen av kategori C i den totala datamängden.
		
		/*length of the vectors*/		
		int vectorLength = 10;

		int sum = 0;
		double probability = 1;
		
		SortedSet classes = data.classes();  		
		String currentClass = (String) classes.first();

		int instanceCounter = 0;				
		
		double currentMax = 0;
		String currentMaxClass = null;

		while (currentClass != null)  {

            //System.out.println(data.instance(instanceCounter).classValue());
			for (int i = 0; i < vectorLength; i++) {
				
//				for (int j = 0; j < 100; j++) {	
				int numOfDocs = 0;
                instanceCounter = 0;
				while(data.instance(instanceCounter).classValue().equals(currentClass)) {
					if (data.instance(instanceCounter).value(i) > 0)
						sum += 1;
		 			numOfDocs++;
					instanceCounter++;
				}
				double termCategory = sum; //numOfDocs;
				double termInstance = instance.value(i);
				if (termInstance > 0)
					probability *= termCategory;			
			}
			
			if (probability >= currentMax) {
				currentMax = probability;
				currentMaxClass = currentClass;
			}
			
			classes.remove(currentClass);
			if(!classes.isEmpty())
                currentClass = (String) classes.first();
            else
                currentClass = null;

		}
		
		return currentMaxClass + currentMax;
		
	}
	
	



}
